<template>
  <div class="questionnaire-list">
    <h1>可填写的问卷列表</h1>
    
    <div v-if="loading" class="loading">正在加载问卷列表...</div>
    <div v-if="error" class="error">{{ error }}</div>
    
    <div v-if="!loading && questionnaires.length === 0" class="empty-list">
      暂无可填写的问卷
    </div>
    
    <div v-if="questionnaires.length > 0" class="questionnaire-cards">
      <div 
        v-for="questionnaire in questionnaires" 
        :key="questionnaire.id"
        class="questionnaire-card"
      >
        <h2>{{ questionnaire.title }}</h2>
        <p v-if="questionnaire.description" class="description">{{ questionnaire.description }}</p>
        <p class="question-count">共 {{ questionnaire.questions.length }} 个问题</p>
        <router-link 
          :to="`/answer/${questionnaire.id}`" 
          class="btn btn-primary"
        >
          填写问卷
        </router-link>
      </div>
    </div>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted } from 'vue';

export default defineComponent({
  setup() {
    const questionnaires = ref([]);
    const loading = ref(true);
    const error = ref('');
    
    const fetchQuestionnaires = async () => {
      loading.value = true;
      error.value = '';
      
      try {
        const response = await fetch('http://localhost:9001/api/questionnaires');
        if (!response.ok) {
          throw new Error('获取问卷列表失败');
        }
        
        const data = await response.json();
        questionnaires.value = data;
      } catch (err) {
        console.error('获取问卷列表时出错:', err);
        error.value = '加载问卷失败: ' + err.message;
      } finally {
        loading.value = false;
      }
    };
    
    onMounted(fetchQuestionnaires);
    
    return {
      questionnaires,
      loading,
      error
    };
  }
});
</script>

<style scoped>
.questionnaire-list {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.empty-list {
  text-align: center;
  padding: 40px;
  background-color: #f9f9f9;
  border-radius: 4px;
  margin-top: 20px;
}

.questionnaire-cards {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.questionnaire-card {
  border: 1px solid #eee;
  border-radius: 4px;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.questionnaire-card h2 {
  margin-top: 0;
  font-size: 1.4em;
}

.description {
  color: #666;
  margin-bottom: 15px;
}

.question-count {
  color: #888;
  font-size: 0.9em;
  margin-bottom: 15px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  text-decoration: none;
  display: inline-block;
}

.btn-primary {
  background-color: #4CAF50;
  color: white;
}

.loading, .error {
  padding: 10px;
  margin-bottom: 15px;
  border-radius: 4px;
}

.loading {
  background-color: #f9f9f9;
}

.error {
  background-color: #ffebee;
  color: #c62828;
}
</style> 